package com.asia5b.a5mall.shop.fragment

import android.os.Bundle
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.launcher.ARouter
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.middleware.base.SimpleFragment
import com.asia5b.a5mall.middleware.logic.viewmodel.shop.ShopAllFragmentVM
import com.asia5b.a5mall.middleware.model.base.ResultModel
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.utils.DisplayUtils
import com.asia5b.a5mall.middleware.utils.newDivider
import com.asia5b.a5mall.middleware.utils.newEmptyView
import com.asia5b.a5mall.middleware.utils.startGoodsDetailActivity
import com.asia5b.a5mall.middleware.widget.GridSpacingItemDecoration
import com.asia5b.a5mall.middleware.widget.refresh.AnimationHelper
import com.asia5b.a5mall.shop.R
import com.asia5b.a5mall.shop.adapter.ShopAllGoodsAdapter
import com.asia5b.a5mall.shop.databinding.FragmentShopallBinding
import kotlinx.android.synthetic.main.fragment_shopall.*

/**
 * Created by zhangyuncai on 2019/12/21.
 * @Note   商店全部商品页面
 */
class ShopAllFragment : SimpleFragment<ShopAllFragmentVM, FragmentShopallBinding>() {
    override val viewModelClazz: Class<ShopAllFragmentVM>
        get() = ShopAllFragmentVM::class.java

    override fun getDataBinding(container: ViewGroup?): FragmentShopallBinding {
        return FragmentShopallBinding.inflate(layoutInflater, container, false)
    }

    val mRecyclerView by lazy { rv_shopall }
    val mDatas = arrayListOf<AbsGoodsModel>()
    lateinit var mAdapter: ShopAllGoodsAdapter
    var shopId: Int = 0
    var keyword: String? = null
    var category: String? = null
    val emptyView by lazy { newEmptyView(mActivity) }

    override fun initView() {
        arguments?.let {

            if (requireArguments().containsKey("shopId")) {
                shopId = requireArguments().getInt("shopId", 0)
            }
            if (requireArguments().containsKey("category")) {
                category = requireArguments().getString("category")
            }
            if (requireArguments().containsKey("keyword")) {
                keyword = requireArguments().getString("keyword")
            }
        }
        setRecyclerView()
    }

    var gridSpacingItemDecoration: GridSpacingItemDecoration? = null
    var linearItemDecoration: DividerItemDecoration? = null
    fun setRecyclerView() {
        gridSpacingItemDecoration?.let {
            mRecyclerView.removeItemDecoration(it)
        }
        linearItemDecoration?.let {
            mRecyclerView.removeItemDecoration(it)
        }
        val selected = iv_shopall_multi.isSelected
        if (selected) {
            mAdapter = ShopAllGoodsAdapter(mDatas, true)
            gridSpacingItemDecoration = GridSpacingItemDecoration(2, DisplayUtils.dip2px(mActivity, 3f), true)
            val gridLayoutManager = GridLayoutManager(mActivity, 2)!!
            mRecyclerView.run {
                layoutManager = gridLayoutManager
                adapter = mAdapter
                addItemDecoration(gridSpacingItemDecoration!!)
            }
        } else {
            mAdapter = ShopAllGoodsAdapter(mDatas, false)
            linearItemDecoration = newDivider(mActivity)
            mRecyclerView.run {
                layoutManager = LinearLayoutManager(mActivity)
                adapter = mAdapter
                addItemDecoration(linearItemDecoration!!)
            }
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val goods3Model = mAdapter.getItem(position) as AbsGoodsModel
            startGoodsDetailActivity(mActivity, goods3Model.absGoodsId)
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = mAdapter.getItem(position) as AbsGoodsModel
            val bundel = Bundle()
            bundel.putBoolean("type", true)
            bundel.putSerializable("data", item)
            bundel.putInt("goodsId", item.absGoodsId)
            val dialog = ARouter.getInstance().build(ActCons.GoodsSpecDF).with(bundel).navigation()
            if (dialog != null && dialog is DialogFragment) {
                dialog.show(childFragmentManager, "GoodsSpecDF")
            }
        }
    }


    override fun initEvent() {
        val changeListener = View.OnClickListener {
            //如果点击的是价格,并且之前已经是选中状态,那么反选状态
            if ((it.id == R.id.ll_shopall_jiage)) {
                if (tv_shopall_jiage.isSelected) {
                    iv_shopall_jiage.isSelected = !iv_shopall_jiage.isSelected
                } else {
                    iv_shopall_jiage.isSelected = true
                }
            } else {
                iv_shopall_jiage.isSelected = false
            }
            changeView(it)

        }
        ll_shopall_zonghe.setOnClickListener(changeListener)
        ll_shopall_xinpin.setOnClickListener(changeListener)
        ll_shopall_tuijian.setOnClickListener(changeListener)
        ll_shopall_xiaoliang.setOnClickListener(changeListener)
        ll_shopall_jiage.setOnClickListener(changeListener)

        //单双列切换
        iv_shopall_multi.setOnClickListener {
            iv_shopall_multi.isSelected = !iv_shopall_multi.isSelected
            setRecyclerView()
            AnimationHelper.reclyTypeAnim(iv_shopall_multi, iv_shopall_multi.isSelected)
        }

        mAdapter.loadMoreModule.setOnLoadMoreListener {
            getDatas(2)
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val model = mAdapter.getItem(position) as AbsGoodsModel
            startGoodsDetailActivity(mActivity, model.absGoodsId)
        }
    }

    override fun startObserver() {
        mViewModel.loadGoodsResultLiveData.observe(this, Observer {
            loadGoodsResult(it)
        })
    }


    fun changeView(v: View) {
        tv_shopall_zonghe.isSelected = v.id == R.id.ll_shopall_zonghe
        tv_shopall_xinpin.isSelected = v.id == R.id.ll_shopall_xinpin
        tv_shopall_tuijian.isSelected = v.id == R.id.ll_shopall_tuijian
        tv_shopall_xiaoliang.isSelected = v.id == R.id.ll_shopall_xiaoliang
        tv_shopall_jiage.isSelected = v.id == R.id.ll_shopall_jiage
        getDatas(1)
    }

    override fun lazyFetchData() {
        changeView(ll_shopall_zonghe)


    }

    fun searchKeyword(keyword: String) {
        this.keyword = keyword
        getDatas(1)
    }

    /**
     * @Note   加载数据
     */
    fun getDatas(refresh: Int) {
        var sort = ""
        if (tv_shopall_zonghe.isSelected) {
            sort = "def_desc"
        } else if (tv_shopall_xinpin.isSelected) {
            sort = "grade_desc"
        } else if (tv_shopall_tuijian.isSelected) {
            sort = "def_desc"
        } else if (tv_shopall_xiaoliang.isSelected) {
            sort = "buynum_desc"
        } else if (tv_shopall_jiage.isSelected) {
            if (iv_shopall_jiage.isSelected) {
                //上升
                sort = "price_asc"
            } else {
                //下降
                sort = "price_desc"
            }

        }
        var map = HashMap<String, Any>()
        map["seller_id"] = "${shopId}"
        map["sort"] = sort
        if (keyword != null && keyword != "") {
            map["keyword"] = keyword!!
        }
        if (category != null && category != "") {
            map["shop_cat_id"] = category!!
        }
        mViewModel.loadGoods(map, refresh)
    }

    fun loadGoodsResult(resultModel: ResultModel<ArrayList<AbsGoodsModel>>) {
        if (emptyView.parent == null) {
            mAdapter.setEmptyView(newEmptyView(mActivity))
        }
        if (resultModel.page == 1) {
            mDatas.clear()
        }
        if (!resultModel.data.isNullOrEmpty()) {
            mAdapter.addData(resultModel.data!!)
        }
        if (resultModel.page < resultModel.sumPage) {
            mAdapter.loadMoreModule.loadMoreComplete()
        } else {
            mAdapter.loadMoreModule.isEnableLoadMore = false
        }
    }

}